package com.tannm.doan.taskmanager.activities;

import java.util.*;

import com.tannm.doan.taskmanager.CommonActivity;
import com.tannm.doan.taskmanager.database.DataRowTask;
import com.tannm.doan.taskmanager.database.DataTable;
import com.tannm.doan.widgets.*;

import com.tannm.doan.taskmanager.R;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

//New task activity
public class ActivityTask extends CommonActivity {
	// private fields
	private Calendar dateDue = null;
	private DataRowTask dataRow = null;
	private DataTable dataTable = null;
	private int iTaskPriority = 2;

	// views
	private TouchEdit edSubject = null;
	private CheckBox chkDone = null;
	private CheckBox chkAlarm = null;
	private Button btnDueDate = null;
	private ImageButton btnDelete = null;
	private ImageButton btnSave = null;

	// priority views
	private Button btnTaskPriorityLow = null;
	private Button btnTaskPriorityDefault = null;
	private Button btnTaskPriorityHigh = null;

	// methods
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.task);

		// initialize objects
		dataRow = new DataRowTask(userdb);
		dataTable = new DataTable(dataRow);

		// check startup mode and open data
		if (getStartMode() == StartMode.EDIT)
			if (!openDataForEdit(dataTable))
				finish();

		// initialize views
		initViews();
		initState();
	}

	@Override
	public void onStart() {
		super.onStart();

	}

	@Override
	public void onResume() {
		super.onResume();

	}

	@Override
	public void onPause() {
		super.onPause();

	}

	private void initViews() {
		edSubject = (TouchEdit) findViewById(R.id.edTaskSubject);
		edSubject.setOnOpenKeyboard(new TouchEdit.OnOpenKeyboard() {
			public void OnOpenKeyboardEvent() {
				KeyboardWidget.open(ActivityTask.this, edSubject.getText()
						.toString());
			}
		});

		chkDone = (CheckBox) findViewById(R.id.chkTaskDone);

		chkAlarm = (CheckBox) findViewById(R.id.chkTaskAlarm);
		btnDueDate = (Button) findViewById(R.id.btnTaskDueDate);

		btnSave = (ImageButton) findViewById(R.id.btnTaskSave);
		btnSave.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				saveData();
			}
		});

		btnDelete = (ImageButton) findViewById(R.id.btnTaskDelete);
		btnDelete.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				deleteData();
			}
		});

		btnDueDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				DateWidget.open(ActivityTask.this, true, dateDue,
						prefs.iFirstDayOfWeek);

			}
		});

		// priority
		btnTaskPriorityLow = (Button) findViewById(R.id.btnTaskPriorityLow);
		btnTaskPriorityLow.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setPriority(3);
			}
		});
		btnTaskPriorityDefault = (Button) findViewById(R.id.btnTaskPriorityDefault);
		btnTaskPriorityDefault.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setPriority(2);
			}
		});
		btnTaskPriorityHigh = (Button) findViewById(R.id.btnTaskPriorityHigh);
		btnTaskPriorityHigh.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setPriority(1);
			}
		});

	}

	public void setPriority(int iPriority) {
		// update global value
		this.iTaskPriority = iPriority;
		// enable buttons
		btnTaskPriorityHigh.setEnabled((iPriority != 1));
		btnTaskPriorityDefault.setEnabled((iPriority != 2));
		btnTaskPriorityLow.setEnabled((iPriority != 3));
		Button btn = null;
		if (iPriority == 1)
			btn = btnTaskPriorityHigh;
		// 1: Daily
		if (iPriority == 2)
			btn = btnTaskPriorityDefault;
		// 2: Weekly
		if (iPriority == 3)
			btn = btnTaskPriorityLow;
		// set focus
		if ((btn != null) && (!btn.isFocused()))
			btn.requestFocus();
	}

	private void initState() {
		// title
		String sSubTitle = utils.getResStr(R.string.titleDefaultAppointment);

		dateDue = Calendar.getInstance();

		// INSERT MODE
		if (getStartMode() == StartMode.NEW) {
			dateDue.setTimeInMillis(0);
			sSubTitle = utils.getResStr(R.string.titleNewTask);
			btnDelete.setVisibility(View.INVISIBLE);
			chkDone.setChecked(false);
			chkDone.setVisibility(View.GONE);
			setPriority(2);
			chkAlarm.setChecked(false);
		}

		// EDIT MODE
		if (getStartMode() == StartMode.EDIT) {
			dateDue.setTimeInMillis(dataRow.getDueDate().getTimeInMillis());
			sSubTitle = utils.getResStr(R.string.titleEditTask);
			edSubject.setText(dataRow.getSubject());
			btnDelete.setVisibility(View.VISIBLE);
			chkDone.setChecked(dataRow.getDone());
			chkDone.setVisibility(View.VISIBLE);
			setPriority(dataRow.getPriority());
			chkAlarm.setChecked(dataRow.getAlarm());
		}

		restoreStateFromFreezeIfRequired();

		setActivityTitle(sSubTitle);
		updateDueDateView();

		// set focus to subject
		edSubject.requestFocus();
		if (getStartMode() == StartMode.EDIT)
			edSubject.setSelection(edSubject.length());
	}

	private void updateDueDateView() {
		if (dateDue.getTimeInMillis() != 0) {
			btnDueDate.setText(utils.getLongDate(dateDue));
		} else {
			btnDueDate.setText(utils.getResStr(R.string.labNoDate));
		}
	}

	public void saveData() {
		if (dateDue.getTimeInMillis() != 0)
			if (dateBeforeNow(dateDue))
				return;

		dataRow.setSubject(edSubject.getText().toString());
		dataRow.setDone(chkDone.isChecked());
		dataRow.setPriority(this.iTaskPriority);
		dataRow.setAlarm(chkAlarm.isChecked());

		if (dateDue.getTimeInMillis() != 0) {
			dataRow.setDueDate(dateDue);
		} else {
			dataRow.setDueDate(null);
		}

		if (saveDataToTable(dataTable))
			closeActivity(dataTable);
	}

	public void deleteData() {
		if (deleteDataFromTable(dataTable))
			closeActivity(dataTable);
	}

	@Override
	public void saveDateValuesBeforeChange(Bundle data) {
		super.saveDateValuesBeforeChange(data);
		if (getStartMode() == StartMode.EDIT) {
			if (dataRow.usingDueDate())
				data.putLong("dateDue", dataRow.getDueDate().getTimeInMillis());
		}
	}

	@Override
	public boolean dateValuesChanged(Bundle data) {
		super.dateValuesChanged(data);
		if (getStartMode() == StartMode.EDIT) {
			if (dataRow.usingDueDate())
				if (dateDue.getTimeInMillis() != data.getLong("dateDue"))
					return true;
		}
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Bundle extras = CommonActivity.getIntentExtras(data);
		if (extras != null) {

			// check for date widget edit request code
			if (requestCode == DateWidget.SELECT_DATE_REQUEST) {
				final long lDate = DateWidget.getSelectedDateOnActivityResult(
						requestCode, resultCode, extras, dateDue);
				if (lDate != -1) {
					updateDueDateView();
				}
			}

			// get KeyboardWidget result
			if ((requestCode == KeyboardWidget.EDIT_TEXT_REQUEST)
					&& (resultCode == RESULT_OK)) {
				String sText = KeyboardWidget.getTextOnActivityResult(
						requestCode, resultCode, extras);
				edSubject.setText(sText);
			}

		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// save controls state
		outState.putString("subject", edSubject.getText().toString());
		outState.putBoolean("alarm", chkAlarm.isChecked());
		outState.putInt("priority", this.iTaskPriority);
		outState.putLong("dateDue", dateDue.getTimeInMillis());
	}

	@Override
	protected void restoreStateFromFreeze() {
		edSubject.setText(freeze.getString("subject"));
		chkAlarm.setChecked(freeze.getBoolean("alarm"));
		setPriority(freeze.getInt("priority"));
		dateDue.setTimeInMillis(freeze.getLong("dateDue"));
	}

}
